''' <summary>
''' Requires a user to check at least one check box and/or limits the number of checkboxes that may be checked in the associated CheckBoxList control.
''' </summary>
''' <remarks></remarks>
Public Class CheckBoxListRequiredFieldValidator
	Inherits System.Web.UI.WebControls.BaseValidator

	Private _ControlToValidate As String = String.Empty
	Private _MinimumCheckBoxesRequired As Int32 = 1
	Private _MaximumCheckBoxesAllowed As Int32 = 0

	''' <summary>
	''' Gets or sets the CheckBoxList to validate.
	''' </summary>
	''' <value>String</value>
	''' <returns>String</returns>
	''' <remarks></remarks>
	<ComponentModel.Description("Gets or sets the CheckBoxList to validate."), ComponentModel.TypeConverter(GetType(CheckBoxListConverter))> _
	Public Shadows Property ControlToValidate() As String
		Get
			Try
				Return _ControlToValidate
			Catch ex As Exception
				Throw
			End Try
		End Get
		Set(ByVal Value As String)
			Try
				_ControlToValidate = Value
			Catch ex As Exception
				Throw
			End Try
		End Set
	End Property

	''' <summary>
	''' The minimum number of checkboxes allowed to be checked.
	''' </summary>
	''' <value>Int32</value>
	''' <returns>Int32</returns>
	''' <remarks></remarks>
	<ComponentModel.Description("The minimum number of checkboxes allowed to be checked.")> _
	Public Property MinimumCheckBoxesRequired() As Int32
		Get
			Try
				Return _MinimumCheckBoxesRequired
			Catch ex As Exception
				Throw
			End Try
		End Get
		Set(ByVal Value As Int32)
			Try
				_MinimumCheckBoxesRequired = Value
			Catch ex As Exception
				Throw
			End Try
		End Set
	End Property

	''' <summary>
	''' The maximum number of checkboxes allowed to be checked. Set this to zero to allow all.
	''' </summary>
	''' <value>Int32</value>
	''' <returns>Int32</returns>
	''' <remarks></remarks>
	<ComponentModel.Description("The maximum number of checkboxes allowed to be checked. Set this to zero to allow all.")> _
	Public Property MaximumCheckBoxesAllowed() As Int32
		Get
			Try
				Return _MaximumCheckBoxesAllowed
			Catch ex As Exception
				Throw
			End Try
		End Get
		Set(ByVal Value As Int32)
			Try
				_MaximumCheckBoxesAllowed = Value
			Catch ex As Exception
				Throw
			End Try
		End Set
	End Property

	Protected Overrides Function ControlPropertiesValid() As Boolean
		Try
			Return True
		Catch ex As Exception
			Throw
		End Try
	End Function

	Protected Overrides Function EvaluateIsValid() As Boolean
		Try
			Return EvaluateIsChecked()
		Catch ex As Exception
			Throw
		End Try
	End Function
	''' <summary>
	''' Server side code to check that the required number of checkboxes are checked.
	''' </summary>
	''' <returns>A boolean value </returns>
	''' <remarks></remarks>
	Protected Function EvaluateIsChecked() As Boolean
		Try
			'---Get the checkboxlist to check
			Dim CheckBoxList As System.Web.UI.WebControls.CheckBoxList = CType(Me.FindControl(_ControlToValidate), System.Web.UI.WebControls.CheckBoxList)

			'---Set the items checked count to zero
			Dim CountChecked As Int32 = 0

			'---Count each item that is checked in the list
			For Each ListItem As System.Web.UI.WebControls.ListItem In CheckBoxList.Items
				If ListItem.Selected Then
					CountChecked += 1
				End If
			Next

			'---After all checkboxes have been counted see if the number of items checked is within the min and max allowed
			If CountChecked >= _MinimumCheckBoxesRequired And (CountChecked <= _MaximumCheckBoxesAllowed Or _MaximumCheckBoxesAllowed = 0) Then
				Return True
			End If

			Return False
		Catch ex As Exception
			Throw
		End Try
	End Function
	''' <summary>
	''' Injects the client side validation script.
	''' </summary>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
		Try
			If EnableClientScript Then
				Call ClientScript()
			End If
			MyBase.OnPreRender(e)
		Catch ex As Exception
			Throw
		End Try
	End Sub

	Protected Overrides Sub AddAttributesToRender(writer As System.Web.UI.HtmlTextWriter)
		MyBase.AddAttributesToRender(writer)
		Dim ClientScriptManager As System.Web.UI.ClientScriptManager = Me.Page.ClientScript
		Dim CheckBoxList As System.Web.UI.WebControls.CheckBoxList = CType(Me.FindControl(_ControlToValidate), System.Web.UI.WebControls.CheckBoxList)
		If System.Web.UI.ScriptManager.GetCurrent(Me.Page) Is Nothing Then
			ClientScriptManager.RegisterExpandoAttribute(Me.ClientID, "controltovalidate", CheckBoxList.ClientID, False)
			ClientScriptManager.RegisterExpandoAttribute(Me.ClientID, "evaluationfunction", "start_verification_" & Me.ClientID, False)
		Else
			System.Web.UI.ScriptManager.RegisterExpandoAttribute(Me, Me.ClientID, "controltovalidate", CheckBoxList.ClientID, False)
			System.Web.UI.ScriptManager.RegisterExpandoAttribute(Me, Me.ClientID, "evaluationfunction", "start_verification_" & Me.ClientID, False)
		End If

	End Sub

	''' <summary>
	''' Client side script to check that the required number of checkboxes are checked.
	''' </summary>
	''' <remarks></remarks>
	Protected Sub ClientScript()
		Try
			Dim ClientScriptManager As System.Web.UI.ClientScriptManager = Me.Page.ClientScript
			Dim ScriptType As Type = GetType(String)
			Dim CheckBoxList As System.Web.UI.WebControls.CheckBoxList = CType(Me.FindControl(_ControlToValidate), System.Web.UI.WebControls.CheckBoxList)

			If Not ClientScriptManager.IsClientScriptBlockRegistered(ScriptType, "CheckBoxListVerification") Then
				Dim StringBuilder As New Text.StringBuilder
				StringBuilder.Append("function checkboxlist_verification(clientID, minimumCheckBoxesRequired, maximumCheckBoxesAllowed)" & vbCrLf)
				StringBuilder.Append("{" & vbCrLf)
				StringBuilder.Append(vbTab & "var val = document.getElementById(clientID);" & vbCrLf)
				StringBuilder.Append(vbTab & "var col = val.getElementsByTagName(""*"");" & vbCrLf)
				StringBuilder.Append(vbTab & "if (col != null )" & vbCrLf)
				StringBuilder.Append(vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "var checked = 0;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "var checkboxcount = 0;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "for (i = 0; i < col.length; i++ )" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & "if (col.item(i).tagName == 'INPUT')" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & vbTab & "checkboxcount += 1;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & vbTab & "if (col.item(i).checked )" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & vbTab & vbTab & "checked += 1;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & vbTab & "}" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & "}" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "}" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "if (checked >= minimumCheckBoxesRequired && (checked <= maximumCheckBoxesAllowed || maximumCheckBoxesAllowed == 0))" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & "return true;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "}" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "else" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "{" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & vbTab & "return false;" & vbCrLf)
				StringBuilder.Append(vbTab & vbTab & "}" & vbCrLf)
				StringBuilder.Append(vbTab & "}" & vbCrLf)
				StringBuilder.Append("}" & vbCrLf)

				If System.Web.UI.ScriptManager.GetCurrent(Me.Page) Is Nothing Then
					ClientScriptManager.RegisterClientScriptBlock(ScriptType, "CheckBoxListVerification", StringBuilder.ToString(), True)
				Else
					System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.Page, ScriptType, "CheckBoxListVerification", StringBuilder.ToString(), True)
				End If
			End If

			If Not ClientScriptManager.IsClientScriptBlockRegistered(ScriptType, "StartVerification" & Me.ClientID) Then
				Dim StringBuilder As New Text.StringBuilder
				StringBuilder.Append("function start_verification_" & Me.ClientID & "(sender)" & vbCrLf)
				StringBuilder.Append("{" & vbCrLf)
				StringBuilder.Append(vbTab & "var isValid = checkboxlist_verification('" & CheckBoxList.ClientID & "', " & _MinimumCheckBoxesRequired & ", " & _MaximumCheckBoxesAllowed & ");" & vbCrLf)
				StringBuilder.Append(vbTab & "return isValid;" & vbCrLf)
				StringBuilder.Append("}" & vbCrLf)

				If System.Web.UI.ScriptManager.GetCurrent(Me.Page) Is Nothing Then
					ClientScriptManager.RegisterClientScriptBlock(ScriptType, "StartVerification" & Me.ClientID, StringBuilder.ToString(), True)
					'ClientScriptManager.RegisterExpandoAttribute(Me.ClientID, "evaluationfunction", "start_verification_" & Me.ClientID)
				Else
					System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.Page, ScriptType, "StartVerification" & Me.ClientID, StringBuilder.ToString(), True)
					'System.Web.UI.ScriptManager.RegisterExpandoAttribute(Me, Me.ClientID, "evaluationfunction", "start_verification_" & Me.ClientID, False)
				End If
			End If
		Catch ex As Exception
			Throw
		End Try
	End Sub
End Class